// sidepanel.js - 智能自动化工具：选择器捕获 + 工作流录制
let capturedSelectors = [];
let workflowActions = [];
let currentWorkflowData = null;
let extractedData = [];
let currentTableInfo = null;
let extractionFields = [];
let isHoverMode = false;
let isRecordingMode = false;
let isDataExtractionMode = false;
let currentMode = 'selector'; // 'selector', 'workflow', or 'data'
let recordingStartTime = null;
let recordingTimer = null;

// DOM 元素
const eventsContainer = document.getElementById('events');
const statusEl = document.getElementById('status');
const clearBtn = document.getElementById('clearBtn');
const exportBtn = document.getElementById('exportBtn');
const hoverModeBtn = document.getElementById('hoverModeBtn');

// 新增的工作流相关元素
const selectorTab = document.getElementById('selectorTab');
const workflowTab = document.getElementById('workflowTab');
const dataTab = document.getElementById('dataTab');
const selectorControls = document.getElementById('selectorControls');
const workflowControls = document.getElementById('workflowControls');
const dataControls = document.getElementById('dataControls');
const workflowStats = document.getElementById('workflowStats');
const dataStats = document.getElementById('dataStats');
const fieldConfig = document.getElementById('fieldConfig');
const recordModeBtn = document.getElementById('recordModeBtn');
const clearWorkflowBtn = document.getElementById('clearWorkflowBtn');
const exportWorkflowBtn = document.getElementById('exportWorkflowBtn');
const recordingDuration = document.getElementById('recordingDuration');
const actionCount = document.getElementById('actionCount');
const currentUrl = document.getElementById('currentUrl');

// 数据抓取相关元素
const selectTableBtn = document.getElementById('selectTableBtn');
const configFieldsBtn = document.getElementById('configFieldsBtn');
const extractDataBtn = document.getElementById('extractDataBtn');
const clearDataBtn = document.getElementById('clearDataBtn');
const exportDataBtn = document.getElementById('exportDataBtn');
const tableSelector = document.getElementById('tableSelector');
const rowCount = document.getElementById('rowCount');
const fieldCount = document.getElementById('fieldCount');
const fieldList = document.getElementById('fieldList');
const addFieldBtn = document.getElementById('addFieldBtn');
const confirmFieldsBtn = document.getElementById('confirmFieldsBtn');

// 检查扩展上下文是否有效
function checkExtensionContext() {
  try {
    return !!(chrome.runtime && chrome.runtime.id);
  } catch (error) {
    console.log('扩展上下文无效:', error);
    return false;
  }
}

// 复制到剪贴板
async function copyToClipboard(text, type) {
  try {
    await navigator.clipboard.writeText(text);
    showCopySuccess(type);
  } catch (err) {
    console.error('复制失败:', err);
    fallbackCopyTextToClipboard(text, type);
  }
}

// 备用复制方法
function fallbackCopyTextToClipboard(text, type) {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.left = '-999999px';
  textArea.style.top = '-999999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      showCopySuccess(type);
    } else {
      showCopyError(type);
    }
  } catch (err) {
    showCopyError(type);
  }
  
  document.body.removeChild(textArea);
}

// 显示复制成功提示
function showCopySuccess(type) {
  const toast = document.createElement('div');
  toast.textContent = `${type} 已复制到剪贴板！`;
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #27ae60;
    color: white;
    padding: 10px 15px;
    border-radius: 6px;
    font-size: 14px;
    z-index: 10000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    animation: slideIn 0.3s ease;
  `;
  
  const style = document.createElement('style');
  style.textContent = `
    @keyframes slideIn {
      from { transform: translateX(100%); opacity: 0; }
      to { transform: translateX(0); opacity: 1; }
    }
  `;
  document.head.appendChild(style);
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.remove();
    style.remove();
  }, 2000);
}

// 显示复制错误提示
function showCopyError(type) {
  const toast = document.createElement('div');
  toast.textContent = `复制 ${type} 失败！`;
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: #e74c3c;
    color: white;
    padding: 10px 15px;
    border-radius: 6px;
    font-size: 14px;
    z-index: 10000;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  `;
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.remove();
  }, 2000);
}

// 模式切换功能
function switchMode(mode) {
  currentMode = mode;

  // 更新标签页状态
  selectorTab.classList.toggle('active', mode === 'selector');
  workflowTab.classList.toggle('active', mode === 'workflow');
  dataTab.classList.toggle('active', mode === 'data');

  // 显示/隐藏对应的控制面板
  selectorControls.classList.toggle('hidden', mode !== 'selector');
  workflowControls.classList.toggle('hidden', mode !== 'workflow');
  dataControls.classList.toggle('hidden', mode !== 'data');
  workflowStats.classList.toggle('hidden', mode !== 'workflow');
  dataStats.classList.toggle('hidden', mode !== 'data');
  fieldConfig.classList.toggle('hidden', mode !== 'data');

  // 更新状态文本
  if (mode === 'selector') {
    statusEl.textContent = '点击"开始选择"按钮，然后在页面上点击元素来捕获选择器';
    showSelectorEvents();
  } else if (mode === 'workflow') {
    statusEl.textContent = '点击"开始录制"按钮，然后在页面上进行操作来录制工作流';
    updateCurrentUrl();
    showWorkflowEvents();
  } else if (mode === 'data') {
    statusEl.textContent = '点击"选择表格"按钮，然后在页面上点击要抓取的表格或列表';
    updateCurrentUrl();
    showDataExtractionEvents();
  }
}

// 显示选择器事件
function showSelectorEvents() {
  eventsContainer.innerHTML = '';
  
  if (capturedSelectors.length === 0) {
    eventsContainer.innerHTML = `
      <div class="empty-state">
        <div class="icon">🎯</div>
        <div>点击"开始选择"，然后在页面上点击元素来捕获选择器</div>
      </div>
    `;
    return;
  }
  
  capturedSelectors.forEach(selector => {
    addCapturedSelector(selector, false);
  });
}

// 显示工作流事件
function showWorkflowEvents() {
  eventsContainer.innerHTML = '';

  if (workflowActions.length === 0) {
    eventsContainer.innerHTML = `
      <div class="empty-state">
        <div class="icon">📝</div>
        <div>点击"开始录制"，然后在页面上进行操作来录制工作流</div>
      </div>
    `;
    return;
  }

  // 按时间戳排序并倒序显示（最新的在顶部）
  const sortedActions = [...workflowActions].sort((a, b) => {
    const timestampA = a.action ? a.action.timestamp : a.timestamp || 0;
    const timestampB = b.action ? b.action.timestamp : b.timestamp || 0;
    return timestampB - timestampA;
  });

  sortedActions.forEach(action => {
    addWorkflowAction(action, false);
  });
}

// 显示数据抓取事件
function showDataExtractionEvents() {
  eventsContainer.innerHTML = '';

  if (extractedData.length === 0) {
    eventsContainer.innerHTML = `
      <div class="empty-state">
        <div class="icon">📊</div>
        <div>点击"选择表格"，然后在页面上选择要抓取的表格或列表区域</div>
      </div>
    `;
    return;
  }

  // 显示抓取的数据表格
  showDataTable(extractedData);
}

// 添加捕获的选择器到界面
function addCapturedSelector(data, prepend = true) {
  if (currentMode !== 'selector') return;
  
  // 清除空状态
  const emptyState = eventsContainer.querySelector('.empty-state');
  if (emptyState) {
    emptyState.remove();
  }

  const selectorDiv = document.createElement('div');
  selectorDiv.className = 'event selector-captured';
  
  const eventHeader = document.createElement('div');
  eventHeader.className = 'event-header';
  
  const eventType = document.createElement('div');
  eventType.className = 'event-type';
  eventType.innerHTML = '🎯 选择器已捕获';
  
  const eventTime = document.createElement('div');
  eventTime.className = 'event-time';
  eventTime.textContent = data.time;
  
  eventHeader.appendChild(eventType);
  eventHeader.appendChild(eventTime);
  
  const eventDetails = document.createElement('div');
  eventDetails.className = 'event-details';
  
  eventDetails.innerHTML = `捕获元素:
标签: ${data.tag}
ID: ${data.id}
Class: ${data.class}
文本: ${data.text}
${data.value}`;
  
  // 添加选择器区域
  if (data.xpath || data.cssSelector) {
    const selectorsDiv = document.createElement('div');
    selectorsDiv.className = 'selectors-section';
    selectorsDiv.style.cssText = `
      margin-top: 10px;
      padding: 10px;
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border-radius: 6px;
      border: 1px solid #dee2e6;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    `;
    
    if (data.xpath) {
      const xpathContainer = document.createElement('div');
      xpathContainer.style.cssText = `
        margin-bottom: 8px;
        background: white;
        border-radius: 4px;
        padding: 6px;
        border: 1px solid #e1e5e9;
      `;
      
      xpathContainer.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
          <span style="font-size: 12px; font-weight: 600; color: #495057; display: flex; align-items: center;">
            <span style="color: #007bff; margin-right: 4px;">📍</span>XPath
          </span>
          <button class="copy-btn" data-text="${data.xpath}" data-type="XPath" style="
            background: #007bff;
            color: white;
            border: none;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s ease;
            box-shadow: 0 1px 2px rgba(0,123,255,0.2);
          " onmouseover="this.style.background='#0056b3'; this.style.transform='translateY(-1px)'" 
             onmouseout="this.style.background='#007bff'; this.style.transform='translateY(0)'">📋 复制</button>
        </div>
        <div style="
          word-break: break-all; 
          font-size: 10px; 
          color: #6c757d; 
          background: #f8f9fa; 
          padding: 4px 6px; 
          border-radius: 3px; 
          border: 1px solid #e9ecef; 
          min-height: 18px;
          max-height: 40px; 
          overflow-y: auto; 
          line-height: 1.3; 
          font-family: 'SFMono-Regular', 'Monaco', 'Consolas', monospace;
          white-space: pre-wrap;
        ">${data.xpath}</div>
      `;
      selectorsDiv.appendChild(xpathContainer);
    }
    
    if (data.cssSelector) {
      const cssContainer = document.createElement('div');
      cssContainer.style.cssText = `
        background: white;
        border-radius: 4px;
        padding: 6px;
        border: 1px solid #e1e5e9;
      `;
      
      cssContainer.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
          <span style="font-size: 12px; font-weight: 600; color: #495057; display: flex; align-items: center;">
            <span style="color: #28a745; margin-right: 4px;">🎯</span>CSS选择器
          </span>
          <button class="copy-btn" data-text="${data.cssSelector}" data-type="CSS选择器" style="
            background: #28a745;
            color: white;
            border: none;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s ease;
            box-shadow: 0 1px 2px rgba(40,167,69,0.2);
          " onmouseover="this.style.background='#1e7e34'; this.style.transform='translateY(-1px)'" 
             onmouseout="this.style.background='#28a745'; this.style.transform='translateY(0)'">📋 复制</button>
        </div>
        <div style="
          word-break: break-all; 
          font-size: 10px; 
          color: #6c757d; 
          background: #f8f9fa; 
          padding: 4px 6px; 
          border-radius: 3px; 
          border: 1px solid #e9ecef; 
          min-height: 18px;
          max-height: 40px; 
          overflow-y: auto; 
          line-height: 1.3; 
          font-family: 'SFMono-Regular', 'Monaco', 'Consolas', monospace;
          white-space: pre-wrap;
        ">${data.cssSelector}</div>
      `;
      selectorsDiv.appendChild(cssContainer);
    }
    
    eventDetails.appendChild(selectorsDiv);
  }

  selectorDiv.appendChild(eventHeader);
  selectorDiv.appendChild(eventDetails);
  
  // 添加复制按钮事件监听器
  const copyBtns = selectorDiv.querySelectorAll('.copy-btn');
  copyBtns.forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const text = btn.getAttribute('data-text');
      const type = btn.getAttribute('data-type');
      copyToClipboard(text, type);
    });
  });
  
  // 添加到界面
  if (prepend) {
    eventsContainer.prepend(selectorDiv);
  } else {
    eventsContainer.appendChild(selectorDiv);
  }
  
  // 添加入场动画
  if (prepend) {
    selectorDiv.style.opacity = '0';
    selectorDiv.style.transform = 'translateY(-20px)';
    requestAnimationFrame(() => {
      selectorDiv.style.transition = 'opacity 0.3s, transform 0.3s';
      selectorDiv.style.opacity = '1';
      selectorDiv.style.transform = 'translateY(0)';
    });
  }
}

// 添加工作流动作到界面
function addWorkflowAction(actionData, prepend = true) {
  if (currentMode !== 'workflow') return;
  
  // 清除空状态
  const emptyState = eventsContainer.querySelector('.empty-state');
  if (emptyState) {
    emptyState.remove();
  }

  const actionDiv = document.createElement('div');
  actionDiv.className = 'event workflow-action';
  
  const eventHeader = document.createElement('div');
  eventHeader.className = 'event-header';
  
  const eventType = document.createElement('div');
  eventType.className = 'event-type';
  
  // 获取动作类型，支持不同的数据结构
  const action = actionData.action || actionData;
  const actionType = action.type || actionData.type;
  eventType.innerHTML = getActionIcon(actionType) + ' ' + getActionLabel(actionType);
  
  const eventTime = document.createElement('div');
  eventTime.className = 'event-time';
  
  // 获取时间戳，支持不同的数据结构
  const timestamp = action.timestamp || actionData.timestamp || 0;
  eventTime.textContent = formatTimestamp(timestamp);
  
  eventHeader.appendChild(eventType);
  eventHeader.appendChild(eventTime);
  
  const eventDetails = document.createElement('div');
  eventDetails.className = 'event-details';
  eventDetails.innerHTML = formatActionDetails(actionData);
  
  actionDiv.appendChild(eventHeader);
  actionDiv.appendChild(eventDetails);
  
  // 添加到界面
  if (prepend) {
    eventsContainer.prepend(actionDiv);
  } else {
    eventsContainer.appendChild(actionDiv);
  }
  
  // 添加入场动画
  if (prepend) {
    actionDiv.style.opacity = '0';
    actionDiv.style.transform = 'translateY(-20px)';
    requestAnimationFrame(() => {
      actionDiv.style.transition = 'opacity 0.3s, transform 0.3s';
      actionDiv.style.opacity = '1';
      actionDiv.style.transform = 'translateY(0)';
    });
  }
}

// 获取动作图标
function getActionIcon(actionType) {
  const icons = {
    'navigate': '🌐',
    'click_element': '🖱️',
    'input_text': '✏️',
    'select_option': '📋',
    'scroll': '📜',
    'wait_element': '⏳',
    'delay': '⏱️'
  };
  return icons[actionType] || '📝';
}

// 获取动作标签
function getActionLabel(actionType) {
  const labels = {
    'navigate': '页面导航',
    'click_element': '点击元素',
    'input_text': '文本输入',
    'select_option': '选择选项',
    'scroll': '页面滚动',
    'wait_element': '等待元素',
    'delay': '延迟等待'
  };
  return labels[actionType] || '未知动作';
}

// 格式化时间戳
function formatTimestamp(timestamp) {
  // 处理无效的时间戳
  if (!timestamp || isNaN(timestamp) || timestamp < 0) {
    return '00:00';
  }
  
  const seconds = Math.floor(timestamp / 1000);
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  // 确保数值有效
  const validMinutes = isNaN(minutes) ? 0 : minutes;
  const validSeconds = isNaN(remainingSeconds) ? 0 : remainingSeconds;
  
  return `${validMinutes.toString().padStart(2, '0')}:${validSeconds.toString().padStart(2, '0')}`;
}

// 格式化动作详情
function formatActionDetails(actionData) {
  const action = actionData.action || actionData;
  const params = action.data ? action.data.parameters : (action.parameters || {});
  
  // 安全获取参数值
  const getParam = (key, defaultValue = '未知') => {
    return params && params[key] ? params[key] : defaultValue;
  };
  
  switch (action.type) {
    case 'navigate':
      return `导航到: ${getParam('url')}`;
    
    case 'click_element':
      return `点击元素: ${getParam('selector')}
选择器类型: ${getParam('selectorType', 'css')}`;
    
    case 'input_text':
      const text = getParam('text', '');
      const displayText = text.length > 30 ? text.substring(0, 30) + '...' : text;
      return `输入文本: "${displayText}"
目标元素: ${getParam('selector')}`;
    
    case 'select_option':
      return `选择选项: ${getParam('text')}
下拉框: ${getParam('selector')}`;
    
    case 'scroll':
      return `滚动到: (${getParam('x', 0)}, ${getParam('y', 0)})
滚动类型: ${getParam('scrollType', 'by_pixels')}`;
    
    default:
      return `动作类型: ${action.type || '未知'}
参数: ${JSON.stringify(params, null, 2)}`;
  }
}

// 更新当前URL显示
function updateCurrentUrl() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs[0]) {
      const url = new URL(tabs[0].url);
      const hostname = url.hostname;
      
      // 简化长域名显示
      let displayText = hostname;
      if (hostname.length > 15) {
        displayText = hostname.substring(0, 12) + '...';
      }
      
      currentUrl.textContent = displayText;
      currentUrl.title = hostname; // 完整域名作为tooltip
    }
  });
}

// 更新录制时长
function updateRecordingDuration() {
  if (!recordingStartTime) return;
  
  const elapsed = Date.now() - recordingStartTime;
  const seconds = Math.floor(elapsed / 1000);
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  recordingDuration.textContent = `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}

// 处理模式切换消息
function handleModeChange(data) {
  if (data.type === 'hover_mode_on') {
    isHoverMode = true;
    updateHoverModeButton();
    updateHoverModeStatus();
  } else if (data.type === 'hover_mode_off') {
    isHoverMode = false;
    updateHoverModeButton();
    updateHoverModeStatus();
  } else if (data.type === 'recording_mode_on') {
    isRecordingMode = true;
    recordingStartTime = Date.now();
    recordingTimer = setInterval(updateRecordingDuration, 1000);
    updateRecordModeButton();
    updateRecordModeStatus();
  } else if (data.type === 'recording_mode_off') {
    isRecordingMode = false;
    recordingStartTime = null;
    if (recordingTimer) {
      clearInterval(recordingTimer);
      recordingTimer = null;
    }
    updateRecordModeButton();
    updateRecordModeStatus();
    
    // 保存工作流数据
    if (data.workflowData) {
      currentWorkflowData = data.workflowData;
    }
  }
}

// 切换悬浮模式
async function toggleHoverMode() {
  if (!checkExtensionContext()) {
    alert('扩展上下文无效');
    return;
  }
  
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) {
      alert('无法获取当前标签页');
      return;
    }
    
    isHoverMode = !isHoverMode;
    
    chrome.tabs.sendMessage(tab.id, {
      action: 'toggleHoverMode',
      enable: isHoverMode
    }, (response) => {
      if (chrome.runtime.lastError) {
        console.error('发送消息失败:', chrome.runtime.lastError);
        alert('无法与页面通信，请刷新页面后重试');
        isHoverMode = false;
        updateHoverModeButton();
        return;
      }
      
      updateHoverModeButton();
      updateHoverModeStatus();
    });
  } catch (error) {
    console.error('切换悬浮模式失败:', error);
    alert('切换失败: ' + error.message);
    isHoverMode = false;
    updateHoverModeButton();
  }
}

// 切换录制模式
async function toggleRecordingMode() {
  if (!checkExtensionContext()) {
    alert('扩展上下文无效');
    return;
  }
  
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) {
      alert('无法获取当前标签页');
      return;
    }
    
    isRecordingMode = !isRecordingMode;
    
    chrome.tabs.sendMessage(tab.id, {
      action: 'toggleRecordingMode',
      enable: isRecordingMode
    }, (response) => {
      if (chrome.runtime.lastError) {
        console.error('发送消息失败:', chrome.runtime.lastError);
        alert('无法与页面通信，请刷新页面后重试');
        isRecordingMode = false;
        updateRecordModeButton();
        return;
      }
      
      updateRecordModeButton();
      updateRecordModeStatus();
    });
  } catch (error) {
    console.error('切换录制模式失败:', error);
    alert('切换失败: ' + error.message);
    isRecordingMode = false;
    updateRecordModeButton();
  }
}

// 更新悬浮模式按钮状态
function updateHoverModeButton() {
  if (isHoverMode) {
    hoverModeBtn.textContent = '🚫 停止选择';
    hoverModeBtn.classList.add('active');
  } else {
    hoverModeBtn.textContent = '🎯 开始选择';
    hoverModeBtn.classList.remove('active');
  }
}

// 更新录制模式按钮状态
function updateRecordModeButton() {
  if (isRecordingMode) {
    recordModeBtn.textContent = '⏹️ 停止录制';
    recordModeBtn.classList.add('active');
  } else {
    recordModeBtn.textContent = '🔴 开始录制';
    recordModeBtn.classList.remove('active');
  }
}

// 更新悬浮模式状态
function updateHoverModeStatus() {
  if (currentMode !== 'selector') return;
  
  if (isHoverMode) {
    statusEl.innerHTML = '🎯 <strong>选择模式已激活</strong>：在页面上点击元素来捕获选择器，按ESC键退出';
  } else {
    statusEl.innerHTML = '点击"开始选择"按钮，然后在页面上点击元素来捕获选择器';
  }
}

// 更新录制模式状态
function updateRecordModeStatus() {
  if (currentMode !== 'workflow') return;
  
  if (isRecordingMode) {
    statusEl.innerHTML = '🔴 <strong>录制模式已激活</strong>：在页面上进行操作来录制工作流，按ESC键退出';
  } else {
    statusEl.innerHTML = '点击"开始录制"按钮，然后在页面上进行操作来录制工作流';
  }
}

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'selector_captured') {
    if (currentMode === 'selector') {
      addCapturedSelector(message);
      capturedSelectors.unshift(message);

      // 限制存储数量
      if (capturedSelectors.length > 50) {
        capturedSelectors = capturedSelectors.slice(0, 50);
      }
    }
  } else if (message.type === 'workflow_action_recorded') {
    if (currentMode === 'workflow') {
      // 插入到正确位置以保持时间顺序
      const messageTimestamp = message.action ? message.action.timestamp : (message.timestamp || 0);
      const insertIndex = workflowActions.findIndex(action => {
        const actionTimestamp = action.action ? action.action.timestamp : (action.timestamp || 0);
        return actionTimestamp > messageTimestamp;
      });

      if (insertIndex >= 0) {
        workflowActions.splice(insertIndex, 0, message);
      } else {
        workflowActions.push(message);
      }

      // 重新渲染工作流事件以保持正确顺序
      showWorkflowEvents();

      // 更新统计
      actionCount.textContent = message.totalActions || workflowActions.length;
    }
  } else if (message.type === 'table_selected') {
    if (currentMode === 'data') {
      currentTableInfo = message.tableInfo;
      
      // 更新统计信息
      tableSelector.textContent = currentTableInfo.type === 'html-table' ? 'HTML表格' : 
                                 currentTableInfo.type === 'repeating-divs' ? '重复结构' :
                                 currentTableInfo.type === 'list' ? '列表' : '容器';
      rowCount.textContent = currentTableInfo.rowCount;
      
      // 自动显示字段配置
      if (currentTableInfo.suggestedFields && currentTableInfo.suggestedFields.length > 0) {
        showFieldConfig(currentTableInfo.suggestedFields);
      }
      
      // 停止选择模式
      isDataExtractionMode = false;
      updateTableSelectionButton();
      updateTableSelectionStatus();
    }
  } else if (message.type === 'extraction_progress') {
    updateExtractionProgress(message.progress);
  } else if (message.type === 'extraction_complete') {
    hideExtractionProgress();
    extractedData = message.data;
    
    if (currentMode === 'data') {
      showDataTable(extractedData);
    }
    
    alert(`数据抓取完成！共提取 ${extractedData.length} 条记录`);
  } else if (message.type === 'extraction_error') {
    hideExtractionProgress();
    alert(`数据抓取失败：${message.error}`);
  } else if (message.type === 'data_extraction_mode_on') {
    isDataExtractionMode = true;
    updateTableSelectionButton();
    updateTableSelectionStatus();
  } else if (message.type === 'data_extraction_mode_off') {
    isDataExtractionMode = false;
    updateTableSelectionButton();
    updateTableSelectionStatus();
  } else if (message.type === 'hover_mode_on' || message.type === 'hover_mode_off' ||
             message.type === 'recording_mode_on' || message.type === 'recording_mode_off') {
    handleModeChange(message);
  }
});

// 清空选择器记录
function clearSelectors() {
  if (capturedSelectors.length === 0) {
    alert('没有记录可清空');
    return;
  }
  
  if (confirm(`确定要清空所有 ${capturedSelectors.length} 条选择器记录吗？`)) {
    capturedSelectors = [];
    if (currentMode === 'selector') {
      eventsContainer.innerHTML = `
        <div class="empty-state">
          <div class="icon">🎯</div>
          <div>点击"开始选择"，然后在页面上点击元素来捕获选择器</div>
        </div>
      `;
      statusEl.innerHTML = '✅ 记录已清空，点击"开始选择"继续捕获选择器';
    }
  }
}

// 清空工作流记录
function clearWorkflow() {
  if (workflowActions.length === 0 && !currentWorkflowData) {
    alert('没有工作流可清空');
    return;
  }
  
  const totalActions = currentWorkflowData ? currentWorkflowData.nodes.length : workflowActions.length;
  if (confirm(`确定要清空当前工作流（${totalActions} 个动作）吗？`)) {
    workflowActions = [];
    currentWorkflowData = null;
    actionCount.textContent = '0';
    recordingDuration.textContent = '00:00';
    
    if (currentMode === 'workflow') {
      eventsContainer.innerHTML = `
        <div class="empty-state">
          <div class="icon">📝</div>
          <div>点击"开始录制"，然后在页面上进行操作来录制工作流</div>
        </div>
      `;
      statusEl.innerHTML = '✅ 工作流已清空，点击"开始录制"继续录制新的工作流';
    }
  }
}

// 导出选择器数据
function exportSelectors() {
  if (capturedSelectors.length === 0) {
    alert('没有数据可导出');
    return;
  }
  
  const dataStr = JSON.stringify({
    exportTime: new Date().toISOString(),
    totalSelectors: capturedSelectors.length,
    selectors: capturedSelectors
  }, null, 2);
  
  const blob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `captured-selectors-${new Date().toISOString().slice(0, 10)}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  alert(`已导出 ${capturedSelectors.length} 条选择器记录`);
}

// 导出工作流数据
function exportWorkflow() {
  let workflowData = currentWorkflowData;
  
  // 如果没有完整的工作流数据，从当前动作生成
  if (!workflowData && workflowActions.length > 0) {
    const nodes = workflowActions.map((action, index) => ({
      id: `action-${index + 1}`,
      type: action.action ? action.action.type : 'unknown',
      position: { x: 100 + (index * 200), y: 100 },
      data: action.action ? action.action.data : {}
    }));
    
    const edges = [];
    for (let i = 0; i < nodes.length - 1; i++) {
      edges.push({
        id: `edge-${i + 1}`,
        source: nodes[i].id,
        target: nodes[i + 1].id,
        sourceHandle: 'success',
        targetHandle: 'input'
      });
    }
    
    workflowData = {
      id: `workflow-partial-${Date.now()}`,
      name: `部分录制的工作流 - ${new Date().toLocaleString()}`,
      description: '从动作序列生成的工作流',
      nodes: nodes,
      edges: edges
    };
  }
  
  if (!workflowData) {
    alert('没有工作流数据可导出');
    return;
  }
  
  const dataStr = JSON.stringify(workflowData, null, 2);
  
  const blob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `workflow-${new Date().toISOString().slice(0, 10)}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  alert(`已导出工作流：${workflowData.nodes.length} 个节点`);
}

// 显示数据表格
function showDataTable(data) {
  if (!data || data.length === 0) {
    eventsContainer.innerHTML = '<div class="empty-state"><div class="icon">📊</div><div>暂无数据</div></div>';
    return;
  }

  const headers = Object.keys(data[0]);
  
  const tableHtml = `
    <div style="background: rgba(255, 255, 255, 0.95); padding: 12px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
      <h4 style="margin: 0 0 10px 0; color: #2c3e50; font-size: 14px;">📊 抓取数据预览</h4>
      <div style="overflow-x: auto; max-height: 400px;">
        <table class="data-table">
          <thead>
            <tr>
              ${headers.map(header => `<th>${header}</th>`).join('')}
            </tr>
          </thead>
          <tbody>
            ${data.slice(0, 50).map(row => `
              <tr>
                ${headers.map(header => `<td title="${row[header] || ''}">${row[header] || ''}</td>`).join('')}
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
      ${data.length > 50 ? `<p style="text-align: center; color: #666; font-size: 12px; margin-top: 10px;">显示前50条，共${data.length}条数据</p>` : ''}
    </div>
  `;
  
  eventsContainer.innerHTML = tableHtml;
}

// 显示字段配置面板
function showFieldConfig(suggestedFields) {
  extractionFields = suggestedFields.map((field, index) => ({
    ...field,
    id: `field_${index}`,
    enabled: true
  }));

  updateFieldList();
  fieldConfig.classList.remove('hidden');
}

// 更新字段列表显示
function updateFieldList() {
  fieldList.innerHTML = '';
  
  extractionFields.forEach(field => {
    const fieldItem = document.createElement('div');
    fieldItem.className = 'field-item';
    fieldItem.innerHTML = `
      <input type="checkbox" class="field-checkbox" ${field.enabled ? 'checked' : ''} data-field-id="${field.id}">
      <input type="text" class="field-name" value="${field.name}" data-field-id="${field.id}">
      <div class="field-selector" title="${field.selector}">${field.selector}</div>
      <div class="field-type">${field.type}</div>
    `;
    fieldList.appendChild(fieldItem);
  });

  // 添加事件监听器
  fieldList.querySelectorAll('.field-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', (e) => {
      const fieldId = e.target.getAttribute('data-field-id');
      const field = extractionFields.find(f => f.id === fieldId);
      if (field) {
        field.enabled = e.target.checked;
      }
      updateFieldCount();
    });
  });

  fieldList.querySelectorAll('.field-name').forEach(input => {
    input.addEventListener('change', (e) => {
      const fieldId = e.target.getAttribute('data-field-id');
      const field = extractionFields.find(f => f.id === fieldId);
      if (field) {
        field.name = e.target.value;
      }
    });
  });

  updateFieldCount();
}

// 更新字段统计
function updateFieldCount() {
  const enabledFields = extractionFields.filter(f => f.enabled);
  fieldCount.textContent = enabledFields.length;
}

// 添加新字段
function addNewField() {
  const newField = {
    id: `field_${Date.now()}`,
    name: `自定义字段${extractionFields.length + 1}`,
    selector: '',
    type: 'text',
    enabled: true
  };
  
  extractionFields.push(newField);
  updateFieldList();
}

// 切换表格选择模式
async function toggleTableSelection() {
  if (!checkExtensionContext()) {
    alert('扩展上下文无效');
    return;
  }

  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) {
      alert('无法获取当前标签页');
      return;
    }

    isDataExtractionMode = !isDataExtractionMode;

    chrome.tabs.sendMessage(tab.id, {
      action: 'toggleDataExtractionMode',
      enable: isDataExtractionMode
    }, (response) => {
      if (chrome.runtime.lastError) {
        console.error('发送消息失败:', chrome.runtime.lastError);
        alert('无法与页面通信，请刷新页面后重试');
        isDataExtractionMode = false;
        updateTableSelectionButton();
        return;
      }

      updateTableSelectionButton();
      updateTableSelectionStatus();
    });
  } catch (error) {
    console.error('切换表格选择模式失败:', error);
    alert('切换失败: ' + error.message);
    isDataExtractionMode = false;
    updateTableSelectionButton();
  }
}

// 更新表格选择按钮状态
function updateTableSelectionButton() {
  if (isDataExtractionMode) {
    selectTableBtn.textContent = '🚫 停止选择';
    selectTableBtn.classList.add('active');
  } else {
    selectTableBtn.textContent = '🎯 选择表格';
    selectTableBtn.classList.remove('active');
  }
}

// 更新表格选择状态
function updateTableSelectionStatus() {
  if (currentMode !== 'data') return;

  if (isDataExtractionMode) {
    statusEl.innerHTML = '🎯 <strong>表格选择模式已激活</strong>：在页面上点击要抓取的表格或列表区域，按ESC键退出';
  } else {
    statusEl.innerHTML = '点击"选择表格"按钮，然后在页面上点击要抓取的表格或列表';
  }
}

// 开始数据抓取
async function startDataExtraction() {
  if (!currentTableInfo || extractionFields.length === 0) {
    alert('请先选择表格并配置字段');
    return;
  }

  const enabledFields = extractionFields.filter(f => f.enabled);
  if (enabledFields.length === 0) {
    alert('请至少选择一个字段');
    return;
  }

  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab) {
      alert('无法获取当前标签页');
      return;
    }

    // 显示抓取进度
    showExtractionProgress();

    // 发送字段配置到content script
    chrome.tabs.sendMessage(tab.id, {
      action: 'setExtractionFields',
      fields: enabledFields
    }, (response) => {
      if (chrome.runtime.lastError || !response.success) {
        hideExtractionProgress();
        alert('设置字段配置失败');
        return;
      }

      // 开始抓取
      chrome.tabs.sendMessage(tab.id, {
        action: 'startDataExtraction'
      }, (response) => {
        if (chrome.runtime.lastError || !response.success) {
          hideExtractionProgress();
          alert('启动数据抓取失败');
        }
      });
    });
  } catch (error) {
    hideExtractionProgress();
    console.error('数据抓取失败:', error);
    alert('抓取失败: ' + error.message);
  }
}

// 显示抓取进度
function showExtractionProgress() {
  const progressHtml = `
    <div class="extraction-status" id="extractionStatus">
      <div>🔄 正在抓取数据...</div>
      <div class="extraction-progress">
        <div class="extraction-progress-bar" id="progressBar" style="width: 0%"></div>
      </div>
      <div id="progressText">准备中...</div>
    </div>
  `;
  
  eventsContainer.innerHTML = progressHtml;
}

// 隐藏抓取进度
function hideExtractionProgress() {
  const status = document.getElementById('extractionStatus');
  if (status) {
    status.remove();
  }
}

// 更新抓取进度
function updateExtractionProgress(progress) {
  const progressBar = document.getElementById('progressBar');
  const progressText = document.getElementById('progressText');
  
  if (progressBar && progressText) {
    progressBar.style.width = `${progress.percentage}%`;
    progressText.textContent = `已处理 ${progress.current}/${progress.total} 行 (${progress.percentage}%)`;
  }
}

// 清空数据抓取记录
function clearDataExtraction() {
  if (extractedData.length === 0 && !currentTableInfo) {
    alert('没有数据可清空');
    return;
  }

  if (confirm('确定要清空所有抓取数据和配置吗？')) {
    extractedData = [];
    currentTableInfo = null;
    extractionFields = [];
    
    tableSelector.textContent = '未选择';
    rowCount.textContent = '0';
    fieldCount.textContent = '0';
    
    fieldConfig.classList.add('hidden');
    
    if (currentMode === 'data') {
      eventsContainer.innerHTML = `
        <div class="empty-state">
          <div class="icon">📊</div>
          <div>点击"选择表格"，然后在页面上选择要抓取的表格或列表区域</div>
        </div>
      `;
      statusEl.innerHTML = '✅ 数据已清空，点击"选择表格"重新开始';
    }
  }
}

// 导出数据
function exportData() {
  if (extractedData.length === 0) {
    alert('没有数据可导出');
    return;
  }

  // 显示导出格式选择
  const format = prompt(`请选择导出格式：
1. CSV (逗号分隔值)
2. JSON (JavaScript对象)  
3. Excel (表格文件)

请输入数字 1-3:`, '1');

  if (!format) return;

  switch (format.trim()) {
    case '1':
      exportDataAsCSV(extractedData);
      break;
    case '2':
      exportDataAsJSON(extractedData);
      break;
    case '3':
      exportDataAsExcel(extractedData);
      break;
    default:
      alert('无效的格式选择');
  }
}

// 导出为CSV
function exportDataAsCSV(data) {
  if (!data || data.length === 0) return;

  const headers = Object.keys(data[0]);
  const csvContent = [
    headers.join(','),
    ...data.map(row => 
      headers.map(header => {
        const value = row[header] || '';
        // 处理包含逗号或引号的值
        if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`;
        }
        return value;
      }).join(',')
    )
  ].join('\n');

  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `extracted-data-${new Date().toISOString().slice(0, 10)}.csv`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  alert(`已导出 ${data.length} 条数据到CSV文件`);
}

// 导出为JSON
function exportDataAsJSON(data) {
  if (!data || data.length === 0) return;

  const jsonData = {
    exportTime: new Date().toISOString(),
    totalRecords: data.length,
    tableInfo: currentTableInfo || {},
    fields: extractionFields.filter(f => f.enabled),
    data: data
  };

  const jsonContent = JSON.stringify(jsonData, null, 2);
  const blob = new Blob([jsonContent], { type: 'application/json;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `extracted-data-${new Date().toISOString().slice(0, 10)}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  alert(`已导出 ${data.length} 条数据到JSON文件`);
}

// 导出为Excel格式(使用HTML table转换)
function exportDataAsExcel(data) {
  if (!data || data.length === 0) return;

  const headers = Object.keys(data[0]);
  
  // 创建Excel HTML格式
  const excelHTML = `
    <html>
      <head>
        <meta charset="utf-8">
        <style>
          table { border-collapse: collapse; width: 100%; }
          th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
          th { background-color: #f2f2f2; font-weight: bold; }
        </style>
      </head>
      <body>
        <table>
          <thead>
            <tr>${headers.map(header => `<th>${header}</th>`).join('')}</tr>
          </thead>
          <tbody>
            ${data.map(row => `
              <tr>${headers.map(header => `<td>${row[header] || ''}</td>`).join('')}</tr>
            `).join('')}
          </tbody>
        </table>
      </body>
    </html>
  `;

  const blob = new Blob([excelHTML], { type: 'application/vnd.ms-excel;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `extracted-data-${new Date().toISOString().slice(0, 10)}.xls`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  alert(`已导出 ${data.length} 条数据到Excel文件`);
}

// 事件监听器
selectorTab.addEventListener('click', () => switchMode('selector'));
workflowTab.addEventListener('click', () => switchMode('workflow'));
dataTab.addEventListener('click', () => switchMode('data'));

hoverModeBtn.addEventListener('click', toggleHoverMode);
recordModeBtn.addEventListener('click', toggleRecordingMode);

// 数据抓取相关事件监听器
selectTableBtn.addEventListener('click', toggleTableSelection);
configFieldsBtn.addEventListener('click', () => {
  if (currentTableInfo && currentTableInfo.suggestedFields) {
    showFieldConfig(currentTableInfo.suggestedFields);
  } else {
    alert('请先选择表格');
  }
});
extractDataBtn.addEventListener('click', startDataExtraction);
clearDataBtn.addEventListener('click', clearDataExtraction);
exportDataBtn.addEventListener('click', exportData);
addFieldBtn.addEventListener('click', addNewField);
confirmFieldsBtn.addEventListener('click', () => {
  fieldConfig.classList.add('hidden');
  alert('字段配置已保存');
});

clearBtn.addEventListener('click', clearSelectors);
clearWorkflowBtn.addEventListener('click', clearWorkflow);

exportBtn.addEventListener('click', exportSelectors);
exportWorkflowBtn.addEventListener('click', exportWorkflow);

// 初始化
function initialize() {
  console.log('智能自动化工具面板已启动');
  switchMode('selector'); // 默认选择器模式
  updateCurrentUrl();
}

// 检查DOM是否已加载
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initialize);
} else {
  initialize();
} 